package com.example.moneybook.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.moneybook.common.WxConstant;
import com.example.moneybook.dto.ResponseResult;
import com.example.moneybook.enums.AppHttpCodeEnum;
import com.example.moneybook.mapper.UserMapper;
import com.example.moneybook.pojo.User;
import com.example.moneybook.service.FileStorageService;
import com.example.moneybook.service.UserService;
import com.example.moneybook.utils.JWTUtils;
import com.example.moneybook.utils.UserNameUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: 包
 * @Date: 2023/3/15 22:48
 * Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(String code) {

        if (code.equals(null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String openid = getOpenId(code);

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper
                .eq("open_id", openid);
        User user = userMapper.selectOne(userQueryWrapper);

        if (user == null){
            User insUser = new User();
            insUser.setOpenId(openid);
            insUser.setLastTime(new Date());
            insUser.setUserName(UserNameUtils.getStringRandom(10));
            userMapper.insert(insUser);
        }else {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper();
            updateWrapper
                    .eq("open_id", openid)
                    .set("last_time", new Date());
            userMapper.update(null, updateWrapper);
        }

        user = userMapper.selectOne(userQueryWrapper);
        if (user != null){
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("opendId", openid);
            String token = JWTUtils.getToken(tokenMap);
            Map<String, Object> res = new HashMap<>();
            res.put("userId", user.getUserId());
            res.put("token", token);
            res.put("headUrl",user.getHeadUrl());
            res.put("userName", user.getUserName());
            return ResponseResult.okResult(res);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 更新用户头像
     * @param filePath
     * @param userId
     * @return
     */
    @Override
    public ResponseResult updateInfo(MultipartFile filePath, String userId) throws IOException {
        if (filePath == null || userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String avatarUrl = null;

        String fileName = UUID.randomUUID().toString().replace("-", "");
        avatarUrl = fileStorageService.uploadImgFile("", fileName+".jpg", filePath.getInputStream());
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper
                .eq("user_id", userId)
                .set("head_url", avatarUrl);
        int update = userMapper.update(null, userUpdateWrapper);
        HashMap<String, Object> res = new HashMap<>();
        res.put("headUrl", avatarUrl);
        if (update == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else {
            return ResponseResult.okResult(res);
        }

    }

    /**
     * 更新用户姓名
     * @param userId
     * @param userName
     * @return
     */
    @Override
    public ResponseResult updateName(String userId, String userName) {
        if (userId.equals(null) || userName.equals(null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper
                .eq("user_id", userId)
                .set("user_name", userName);
        int update = userMapper.update(null, userUpdateWrapper);
        if (update == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else {
            return ResponseResult.okResult(userName);
        }
    }

    public String getOpenId(String code){
        String authUrl = WxConstant.URL +"&appid="+WxConstant.APP_ID+"&secret="+WxConstant.APP_SECRET+"&js_code="+code;
        String res = HttpUtil.get(authUrl);
        JSONObject jsonObject = JSONUtil.parseObj(res);
        String openid = jsonObject.getStr("openid");
        return openid;
    }
}
